package com.hxgis.oc.ws;

import cn.hutool.json.JSONObject;
import com.hxgis.oc.util.ds.FileDatabase;
import com.hxgis.oc.product.base.ProduceTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class WSClientManager extends WSProductFactoryImp{
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    private String genKey(Session session,String sid){
        return sid + session.toString();
    }

    public boolean registerClient(Session session,String sid){
        String key = genKey(session,sid);
        sessionPools.put(key, session);
        try {
            sendMessage(session, "connected to OC WS.");
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return true;
    }

    public void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
                session.getBasicRemote().sendText(message);
            }
        }
    }

    public void closeClient(Session session,String sid) {
        String key = genKey(session,sid);
        sessionPools.remove(key);
    }

    @Override
    protected void onPublish(ProduceTask o) {
        String productType = o.getProductType();
        if(!accept(productType)){
            return;
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.set(FileDatabase.FieldID,o.getFileID());
        jsonObject.set(FileDatabase.FieldName,o.getOutputFile().getName());
        jsonObject.set("productType",o.getProductType());
        jsonObject.set("dataSet",o.getDataSet());
        String message = jsonObject.toString();

        for(Session session : sessionPools.values())
        {
            try {
                sendMessage(session,message);
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
    }
}
